package com.service.kaptcha.utils;

import org.apache.commons.codec.binary.Base64;
//import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * 图片和Base64转换
 * https://www.cnblogs.com/libra0920/p/5754356.html
 */
public class Base64Utils {


    /**
     * 字节流转Base64
     * @param data 图片字节流
     * @return Base64Sting
     */
    public static String getImageBase64String(byte[] data) {
//        return new BASE64Encoder().encode(data);
        return new String(Base64.encodeBase64(data));
    }


    /**
     * 图片转Base64
     * @param imgFilePath 图片路径
     * @return Base64
     */
    public static String getImageBase64String(String imgFilePath) throws IOException {
        //将文件转换成输入流
        InputStream inputStream = new FileInputStream(imgFilePath);
        byte[] data = new byte[inputStream.available()];
        //将输入流写入数组
        inputStream.read(data);
        inputStream.close();
        // 加密
//        return new BASE64Encoder().encode(data);
        return new String(Base64.encodeBase64(data));
    }

    /**
     * Base64转图片
     *
     * @param imgStr Base64代码
     * @param path   储存路径
     * @return boolean
     */
    public static boolean generateImage(String imgStr, String path) {
        if (imgStr == null)
            return false;
//        BASE64Decoder decoder = new BASE64Decoder();
        Base64 base64 = new Base64();
        try {
            // 解密
//            byte[] b = decoder.decodeBuffer(imgStr);
            byte[] b = base64.decode(imgStr);
            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(path);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
